import { Button, ButtonProps, Typography, App } from 'antd';
import { MouseEvent, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from 'src/store';

const Link = Typography.Link;

interface IProps extends ButtonProps {
  permission: string;
  children?: React.ReactNode;
  useHide?: boolean;
}

export default function PermissionButton(props: IProps) {
  const { permission, children, type, className, style, onClick, ...rest } = props;
  const { message } = App.useApp();

  const permissions = useSelector((state: RootState) => state.permission.buttons);

  const hasPermission = useMemo(() => {
    return permissions.includes(permission);
  }, [permissions, permission]);

  const onClickHandler = (e: MouseEvent<HTMLElement>) => {
    if (hasPermission) {
      onClick?.(e);
    } else {
      message.warning('该账号暂无当前操作权限');
    }
  };

  return (
    <>
      {type === 'link' ? (
        <Link className={className} onClick={onClickHandler} style={style} {...rest}>
          {children}
        </Link>
      ) : (
        <Button {...rest} onClick={onClickHandler} type={type} className={className} style={style}>
          {children}
        </Button>
      )}
    </>
  );
}
